package controller

import (
	"errors"
	"fmt"
	"parking-lot-go-dingding/model/cars"
	"parking-lot-go-dingding/model/dingtalk/system"
	"parking-lot-go-dingding/model/view"
	"strings"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Seeting(c *gin.Context) {
	requestStruct := struct {
		CorpId string `json:"corp_id"`
		Userid string `json:"userid"`
	}{}

	//接收加密串
	if err := c.ShouldBindJSON(&requestStruct); err != nil {
		Fail(c, "json接收失败")
		return
	}

	var err error

	//绑定会员数量
	var membersDingtalkViewStruct view.MembersDingtalkViewStruct
	memberCount, err := membersDingtalkViewStruct.Count(map[string]interface{}{
		"member_dingtalk_corpid": requestStruct.CorpId,
	})

	if err != nil {
		Fail(c, fmt.Sprintf("会员人数查询失败%s", err.Error()))
		return
	}

	//绑定车辆数量
	var carsStruct cars.CarsStruct
	carCount, err := carsStruct.Count(map[string]interface{}{
		"tripartite_voucher": requestStruct.CorpId,
	})
	if err != nil {
		Fail(c, "绑定车牌查询失败")
		return
	}

	//查询用户
	member, err := membersDingtalkViewStruct.First(map[string]interface{}{
		"member_dingtalk_corpid": requestStruct.CorpId,
		"member_dingtalk_userid": requestStruct.Userid,
	})
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		Fail(c, "会员信息查询失败")
		return
	}

	//手机号
	mobile := "号码未绑定"
	if member.MemberMobile != "" {
		mobile = fmt.Sprintf("%s%s%s", member.MemberMobile[:3], strings.Repeat("*", 4), member.MemberMobile[7:])
	}

	//公司信息查询
	var dingtalkSystemCorpStruct system.DingtalkSystemCorpStruct
	corp, err := dingtalkSystemCorpStruct.First(requestStruct.CorpId)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		Fail(c, "企业信息查询失败")
		return
	}

	Success(c,
		map[string]interface{}{
			"member_number": memberCount,
			"car_number":    carCount,
			"mobile":        mobile,
			"corp":          corp,
		})

}
